package cn.lg.soar.common.util.jackson.deserializer;

import cn.lg.soar.common.data.dict.IDict;
import cn.lg.soar.common.util.EnumUtils;
import cn.lg.soar.common.util.reflect.ReflectUtil;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;

import java.io.IOException;
import java.lang.reflect.Field;

/**
 * IDict 反序列化
 * @author luguoxiang
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
public class EnumDeserializer extends JsonDeserializer<Enum> {

    public static final EnumDeserializer instance = new EnumDeserializer();

    private EnumDeserializer(){}

    @Override
    public Enum deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        Object currentValue = jsonParser.getCurrentValue();
        Field field = ReflectUtil.getField(currentValue.getClass(), jsonParser.currentName());
        Class<?> type = field.getType();
        if (IDict.class.isAssignableFrom(type)) {
            return (Enum) EnumUtils.valueOf((Class<? extends IDict<?>>) type, jsonParser.getText());
        }
        return Enum.valueOf((Class<? extends Enum>)type, jsonParser.getText());
    }

}
